package com.chj.filter;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.PathMatcher;

import com.chj.util.JsonUtil;
import com.chj.util.UrlPathUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

public abstract class BaseZuulFilter extends ZuulFilter implements FilterPathMatcher {

	protected Logger log = LoggerFactory.getLogger(this.getClass());

	protected boolean enable;
	protected int order;
	protected String[] includePattern;
	protected String[] excludePattern;
	protected String filterType;

	@Override
	public boolean shouldFilter() {
		// 是否执行该过滤器，true代表需要过滤
		RequestContext ctx = RequestContext.getCurrentContext();
		return match(ctx.getRequest());
	}

	@Autowired
	PathMatcher pathMatcher;

	@Override
	public boolean match(HttpServletRequest request) {
		String[] includePatterns = this.getIncludePattern();
		String[] excludePatterns = this.getExcludePattern();
		log.info("IncludePattern:	" + JsonUtil.getJson(this.getIncludePattern()));
		log.info("ExcludePattern:	" + JsonUtil.getJson(this.getExcludePattern()));
		log.info("CurrentRequestUrl:	" + JsonUtil.getJson(UrlPathUtil.getServletPath(request)));
		if (excludePatterns != null) {
			for (int i = 0; i < excludePatterns.length; i++) {
				boolean rs = pathMatcher.match(excludePatterns[i], UrlPathUtil.getServletPath(request));
				if (rs) {
					return !rs;
				}
			}
		}
		boolean rs = false;
		if (includePatterns != null) {
			for (int i = 0; i < includePatterns.length; i++) {
				rs = pathMatcher.match(includePatterns[i], UrlPathUtil.getServletPath(request));
				if (rs) {
					break;
				}
			}
		}
		return rs;
	}

	public boolean isEnable() {
		return enable;
	}

	public void setEnable(boolean enable) {
		this.enable = enable;
	}

	public int getOrder() {
		return order;
	}

	public void setOrder(int order) {
		this.order = order;
	}

	public String[] getIncludePattern() {
		return includePattern;
	}

	public void setIncludePattern(String[] includePattern) {
		this.includePattern = includePattern;
	}

	public String[] getExcludePattern() {
		return excludePattern;
	}

	public void setExcludePattern(String[] excludePattern) {
		this.excludePattern = excludePattern;
	}

	public String getFilterType() {
		return filterType;
	}

	public void setFilterType(String filterType) {
		this.filterType = filterType;
	}

	public PathMatcher getPathMatcher() {
		return pathMatcher;
	}

	public void setPathMatcher(PathMatcher pathMatcher) {
		this.pathMatcher = pathMatcher;
	}

}
